package com.njmd.mdbs.web.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.njmd.framework.base.BaseCrudServiceImpl;
import com.njmd.framework.dao.BaseHibernateDAO;
import com.njmd.framework.dao.Page;
import com.njmd.framework.dao.PropertyFilter;
import com.njmd.mdbs.web.constants.ResultConstants;
import com.njmd.mdbs.web.entity.sys.SysConfig;
import com.njmd.mdbs.web.service.SysConfigService;

/**
 * 系统配置管理
 * 
 * @author sunqw
 * @since 2013.10.12
 */
@Service
@Transactional(readOnly = true)
public class SysConfigServiceImpl extends BaseCrudServiceImpl<SysConfig, Long> implements SysConfigService
{

	@Autowired
	@Override
	@Qualifier(value = "sysConfigDAO")
	public void setBaseDao(BaseHibernateDAO<SysConfig, Long> baseDao)
	{
		this.baseDao = baseDao;
	}

	@Override
	public List<SysConfig> getLicenseParams()
	{
		String hql = "from SysConfig as model where model.parentId =? order by model.id asc";
		return baseDao.findByHql(hql, 1l);
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public void update(String code, String value)
	{
		SysConfig sysConfig = baseDao.findUnique("code", code);
		if (null != sysConfig)
		{
			sysConfig.setValue(value);
			baseDao.update(sysConfig);
		}
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public void update(Map<String, String> params)
	{
		if (null != params && params.size() > 0)
		{
			for (Map.Entry<String, String> entry : params.entrySet())
				update(entry.getKey(), entry.getValue());
		}
	}

	@Override
	public SysConfig getConfigByCode(String code)
	{
		SysConfig sysConfig = baseDao.findUnique("code", code);
		return sysConfig;
	}

	@Override
	public Page query(Page page, List<PropertyFilter> filters) throws Exception
	{
		Page pageTemp = baseDao.findByPage(page, filters);
		List resultList = pageTemp.getResult();
		pageTemp.setResult(resultList);
		return pageTemp;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int save(SysConfig sysConfigDTO) throws Exception
	{
		SysConfig sysConfig = new SysConfig();
		BeanUtils.copyProperties(sysConfig, sysConfigDTO);

		if (!sysConfig.getConfigName().equals(""))
		{
			baseDao.save(sysConfig);

			return ResultConstants.SAVE_SUCCEED;
		}
		return ResultConstants.SAVE_ERROR;
	}

	@Override
	public SysConfig findById(Long id) throws Exception
	{
		SysConfig sysConfig = baseDao.findById(id);
		return sysConfig;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int update(SysConfig sysConfig) throws Exception
	{
		SysConfig sys = baseDao.findById(sysConfig.getId());

		if (null == sys)
			return ResultConstants.UPDATE_RECORD_NOT_EXIST;

		sys.setParentId(sysConfig.getParentId());
		sys.setCode(sysConfig.getCode());
		sys.setConfigDesc(sysConfig.getConfigDesc());
		sys.setConfigName(sysConfig.getConfigName());
		sys.setDefaultVal(sysConfig.getDefaultVal());
		sys.setViewFlag(sysConfig.getViewFlag());
		sys.setValType(sysConfig.getValType());
		sys.setValidateRule(sysConfig.getValidateRule());

		baseDao.update(sys);

		return ResultConstants.UPDATE_SUCCEED;
	}

	// @Override
	// public List query() throws Exception
	// {
	// List s=baseDao.findAll();
	//
	// return s;
	// }
	@Override
	public int getCountParentId(Long id)
	{
		List<SysConfig> show = baseDao.findByHql("from SysConfig where parentId = " + id);
		return show.size();
	}

	@Override
	public List<SysConfig> findAllType()
	{
		List<SysConfig> type = baseDao.findByHql("from SysConfig where parentId =0");
		return type;
	}

	@Override
	public List<SysConfig> findAllItem()
	{
		List<SysConfig> item = baseDao.findByHql("from SysConfig where parentId !=0");
		return item;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public String getUploadfile(MultipartFile file, Long id) throws Exception
	{
		String path = "";
		try
		{
			File newFile = new File(this.getWebRootPath() + File.separator + "upload" + File.separator + "sys_config_upload"
					+ File.separator);
			String name = id.toString();
			if (!newFile.exists())
			{
				newFile.mkdirs();
			}
			deleteFilesLikeName(newFile, name);
			InputStream fr = file.getInputStream();

			String extension = FilenameUtils.getExtension(file.getOriginalFilename());
			FilenameUtils.getBaseName(file.getOriginalFilename());
			String fileType = extension.toLowerCase();
			SysConfig entity = this.findById(id);
			if (fileType.equals("bmp") || fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png")
					|| fileType.equals("gif"))
			{
				entity.setFileType("1");
			}
			else
			{
				entity.setFileType("2");
			}

			path = this.getWebRootPath() + File.separator + "upload" + File.separator + "sys_config_upload" + File.separator + id + "."
					+ extension;
			FileOutputStream fw = new FileOutputStream(path);

			byte buffer[] = new byte[1444];
			while (fr.read(buffer) != -1)
			{
				fw.write(buffer);
			}
			fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。
			fr.close();
			this.update(entity);
		}
		catch (Exception e)
		{
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}
		return path;
	}

	public void deleteFilesLikeName(File file, String likeName)
	{
		if (file.isFile())
		{
			// 是文件
			String temp = file.getName().substring(0, file.getName().lastIndexOf("."));
			if (temp.indexOf(likeName) != -1)
			{
				file.delete();
			}
		}
		else
		{
			// 是目录
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
			{
				deleteFilesLikeName(files[i], likeName);
			}
		}
	}
}
